<?php

/**
 * ECSHOP 数据采集管理程序
 * ============================================================================
 * * 版权所有 2005-2012 上海商派网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: YunGaZeon $
 * $Blog: http://www.cnblogs.com/GaZeon/ $
 * $Id: collection.php start:2017-07-09 end:2017-8-16 YunGaZeon $
*/

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
require(dirname(__FILE__) . '/includes/lib_format.php');
require(ROOT_PATH . '/includes/cls_image.php');
require(dirname(__FILE__) . '/includes/lib_collection.php');

date_default_timezone_set('Asia/Shanghai');
/* act操作项的初始化 */
if (empty($_REQUEST['act']))
{
    $_REQUEST['act'] = 'node_manage';
}
else
{
    $_REQUEST['act'] = trim($_REQUEST['act']);
}


/*------------------------------------------------------ */
//-- 采集节点列表页面
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'node_manage')
{
	//检查权限
	admin_priv('node_manage');
	
	$smarty->assign('title','采集页');
	
	/* 取得过滤条件 */
	$smarty->assign('ur_here',      '商品采集节点管理');
    $smarty->assign('full_page',    1);
    $nodes = get_node_list(true);
    $smarty->assign('node_list',       $nodes['arr']);
    $smarty->assign('filter',          $nodes['filter']);
    $smarty->assign('record_count',    $nodes['record_count']);
    $smarty->assign('page_count',      $nodes['page_count']);
	$smarty->assign('cat_id',          $nodes['cat_id']);
	$smarty->assign('keyword',         $nodes['keyword']);
	
	$smarty->assign('action_link',  ['href' => 'collection.php?act=node_add', 'text' => '添加节点']);
	
	/*获取商品类型*/
	$sql = "select cat_id,cat_name FROM {$ecs->table('goods_type')} WHERE enabled = 1";
    $cat_list=$db->getAll($sql);
	$smarty->assign('cats',$cat_list);
	
    $sort_flag  = sort_flag($nodes['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);
	
	//获得查询时间和次数，并赋值给smarty
	assign_query_info();
	$smarty->display('collection_list.htm');
}
/*------------------------------------------------------ */
//-- 采集节点翻页，排序
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'node_query')
{
	//检查权限
    admin_priv('node_manage');
	
	$nodes=get_node_list(true);
	$smarty->assign('node_list',	   $nodes['arr']);
    $smarty->assign('filter',          $nodes['filter']);
    $smarty->assign('record_count',    $nodes['record_count']);
    $smarty->assign('page_count',      $nodes['page_count']);
	$smarty->assign('cat_id',          $nodes['cat_id']);
	$smarty->assign('keyword',         $nodes['keyword']);

    $sort_flag  = sort_flag($nodes['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);;

    make_json_result($smarty->fetch('collection_list.htm'), '',
        array('filter' => $nodes['filter'], 'page_count' => $nodes['page_count']));
}
/*------------------------------------------------------ */
//-- 添加节点
/*------------------------------------------------------ */
else if ($_REQUEST['act'] == 'node_add')
{
    /* 权限判断 */
    admin_priv('node_manage');

	/* 获取分类信息*/
    $sql = "select cat_id,cat_name FROM {$ecs->table('goods_type')} WHERE enabled = 1";
    $cat_list=$db->getAll($sql);

    $smarty->assign('ur_here','添加节点');

	$smarty->assign('action_link', array('text' => '返回节点列表', 'href' => 'collection.php?act=node_manage'));
	$smarty->assign('form_action', 'node_insert');
	$smarty->assign('cat_list',$cat_list);
	
	clear_cache_files(); // 清除相关的缓存文件
    assign_query_info();
    $smarty->display('collection_info.htm');
}
/*------------------------------------------------------ */
//-- 检查节点名
/*------------------------------------------------------ */
else if ($_REQUEST['act'] == 'node_namecheck')
{
	/* 权限判断 */
    admin_priv('node_manage');
	$name=trim($_REQUEST['name']);
	if(!empty($name))
	{
		$sql="SELECT count(id) FROM {$ecs->table('collection_node')} WHERE name='{$name}'";
		if($db->getOne($sql)>0)
			make_json_error(1);
		else
			make_json_result(0);
	}
}
/*------------------------------------------------------ */
//-- 插入节点
/*------------------------------------------------------ */
else if ($_REQUEST['act'] == 'node_insert')
{
    /* 权限判断 */
    admin_priv('node_manage');
	
	//检查数据
	$data=check_post_data($_REQUEST,TRUE);
	
	/*添加节点配置入库*/
	$db->autoExecute($ecs->table('collection_node'), $data);
    $nodeid = $db->insert_id();
	
	/*添加扩展配置信息入库*/
	$sql = "INSERT INTO ".$ecs->table('collection_diyrule')."(nodeid, attrid, attrname, rule_content, rule_except) VALUES ";
    $_rule_empty=TRUE;
	if(count($data['attrid'])>0)
	{
		foreach($data['attrid'] as $i=>$attrid)
		{
			if(!empty($data['rule_content'][$i]))
			{
				$_rule_empty=FALSE;
				$sql.="('{$nodeid}','{$attrid}','{$data['attrname'][$i]}','{$data['rule_content'][$i]}','{$data['rule_except'][$i]}'),";
			}
		}
		if($_rule_empty==FALSE)
		{
			$sql=trim($sql,',');		 
			$db->query($sql);
			$rule_rows = $db->affected_rows();
		}
	}
	
	/*添加内容替换规则入库*/
	$_rule_empty=TRUE;
	$sql = "INSERT INTO {$ecs->table('collection_replace')} (nodeid, replace_from,replace_to) VALUES ";
	if(count($data['replace_from'])>0)
	{
		foreach($data['replace_from'] as $_i=>$_from)
		{
			$_rule_empty=FALSE;
			$_from=addslashes($_from);
			$_to=addslashes($data['replace_to'][$_i]);
			$sql.="('{$nodeid}','{$_from}','{$_to}'),";	
		}
		if($_rule_empty==FALSE)
		{
			$sql=trim($sql,',');		 
			$db->query($sql);
			$rule_rows = $db->affected_rows();
		}
	}
	
	admin_log($data['name'].'-'.$nodeid,'add','node_manage');
    clear_cache_files(); // 清除相关的缓存文件
    sys_msg('添加节点成功',0,[['text'=>'添加节点成功！！！','link'=>'collection.php']]);
}

/*------------------------------------------------------ */
//-- 添加/更改节点时获取的商品属性
/*------------------------------------------------------ */
else if ($_REQUEST['act'] == 'get_attr_list')
{
	//检查权限
	admin_priv('node_manage');
	$cat_id=isset($_POST['cat_id'])?trim($_POST['cat_id']):0;
	if(!$cat_id)
		die(0);
	
	$sql = "SELECT attr_id,attr_name FROM " . $ecs->table('attribute') . " WHERE cat_id = {$cat_id}";
    $attr_list=$db->getAll($sql);
	die(json_encode($attr_list));
}

/*------------------------------------------------------ */
//-- 修改节点
/*------------------------------------------------------ */
else if ($_REQUEST['act'] == 'node_edit')
{
    /* 权限判断 */
    admin_priv('node_manage');
	
	clear_cache_files();

	/* 获取节点信息*/
    $sql = "select * FROM {$ecs->table('collection_node')} WHERE id = {$_REQUEST['nodeid']}";
    $node=$db->getRow($sql);

	/*获取自定义规则*/
	$sql = "select * FROM {$ecs->table('collection_diyrule')} WHERE nodeid = {$_REQUEST['nodeid']}";
    $attrrule=$db->getAll($sql);
	
	//获取商品类型
	$sql = "select cat_name FROM {$ecs->table('goods_type')} WHERE enabled = 1 and cat_id = {$node['catid']}";
    $cat_name=$db->getOne($sql);
	
	//获取商品属性配置
	$sql = "SELECT a.attr_id,a.attr_name,b.* FROM {$ecs->table('attribute')} a LEFT JOIN {$ecs->table('collection_diyrule')} b on a.attr_id=b.attrid WHERE a.cat_id = {$node['catid']} group by a.attr_id";
    $attr_rule=$db->getAll($sql);

	/* 获取分类信息*/
    $sql = "select cat_id,cat_name FROM " . $ecs->table('goods_type') . " WHERE enabled = 1";
    $cat_list=$db->getAll($sql);
	
	/* 获取额外字段信息*/
    $sql = "select * FROM {$ecs->table('collection_field')} WHERE nodeid = {$_REQUEST['nodeid']}";
    $fields=$db->getAll($sql);
	
	/* 获取替换规则*/
    $sql = "select * FROM {$ecs->table('collection_replace')} WHERE nodeid = {$_REQUEST['nodeid']}";
    $replaces=$db->getAll($sql);
	
    $smarty->assign('ur_here','修改节点');
	$smarty->assign('form_action', 'node_update');
	
	$smarty->assign('node',$node);
	$smarty->assign('attrrule',$attrrule);
	
	$smarty->assign('attr_rule',$attr_rule);
	$smarty->assign('cat_name',$cat_name);
	$smarty->assign('cat_list',$cat_list);
	
	$smarty->assign('fields',$fields);
	$smarty->assign('replaces',$replaces);
	
	$smarty->assign('action_link', array('text' => '返回节点列表', 'href' => 'collection.php?act=node_manage'));
	
	clear_cache_files();
    assign_query_info();
    $smarty->display('collection_info.htm');
}
/*------------------------------------------------------ */
//-- 更新节点
/*------------------------------------------------------ */
else if ($_REQUEST['act'] == 'node_update')
{
    /* 权限判断 */
    admin_priv('node_manage');
	
	//检查数据
	$data=check_post_data($_REQUEST);

	/*更新节点配置入库*/
	$db->autoExecute($ecs->table('collection_node'), $data,'UPDATE',"id={$data['nodeid']}");
	$affected_rows = $db->affected_rows();

	/*删除属性规则*/
	$sql="DELETE FROM {$ecs->table('collection_diyrule')} WHERE nodeid={$data['nodeid']}";
	$db->query($sql);
    $affected_rows = $db->affected_rows();

	/*添加属性规则信息入库*/
	$_rule_empty=TRUE;
	$sql = "INSERT INTO {$ecs->table('collection_diyrule')} (nodeid, attrid,attrname, rule_content, rule_except,rule_replace) VALUES ";
	if(count($data['attrid'])>0)
	{
		foreach($data['attrid'] as $i=>$attrid)
		{
			if(!empty($data['rule_content'][$i]))
			{
				$_rule_empty=FALSE;
				$sql.="('{$data['nodeid']}','{$attrid}','{$data['attrname'][$i]}','{$data['rule_content'][$i]}','{$data['rule_except'][$i]}','{$data['rule_replace'][$i]}'),";
			}
		}
		if($_rule_empty==FALSE)
		{
			$sql=trim($sql,',');		 
			$db->query($sql);
			$rule_rows = $db->affected_rows();
		}
	}
	
	/*添加额外字段规则信息入库*/
	$_rule_empty=TRUE;
	$sql="DELETE FROM {$ecs->table('collection_field')} WHERE nodeid={$data['nodeid']}";
	$db->query($sql);
	$sql = "INSERT INTO {$ecs->table('collection_field')} (nodeid, field_name,field_rule_match, field_rule_include, field_rule_except,field_rule_replace) VALUES ";
	if(count($data['field_name'])>0)
	{
		foreach($data['field_name'] as $i=>$name)
		{
			if(!empty($data['field_rule_match'][$i]))
			{
				$_rule_empty=FALSE;
				$sql.="('{$data['nodeid']}','{$name}','{$data['field_rule_match'][$i]}','{$data['field_rule_include'][$i]}','{$data['field_rule_except'][$i]}','{$data['field_rule_replace'][$i]}'),";
			}
		}
		if($_rule_empty==FALSE)
		{
			$sql=trim($sql,',');		 
			$db->query($sql);
			$rule_rows = $db->affected_rows();
		}
	}
	
	/*添加内容替换规则入库*/
	$_rule_empty=TRUE;
	$sql="DELETE FROM {$ecs->table('collection_replace')} WHERE nodeid={$data['nodeid']}";
	$db->query($sql);
	$sql = "INSERT INTO {$ecs->table('collection_replace')} (nodeid, replace_from,replace_to) VALUES ";
	if(count($data['replace_from'])>0)
	{
		foreach($data['replace_from'] as $_i=>$_from)
		{
			$_rule_empty=FALSE;
			$_from=addslashes($_from);
			$_to=addslashes($data['replace_to'][$_i]);
			$sql.="('{$data['nodeid']}','{$_from}','{$_to}'),";	
		}
		if($_rule_empty==FALSE)
		{
			$sql=trim($sql,',');		 
			$db->query($sql);
			$rule_rows = $db->affected_rows();
		}
	}

	admin_log($data['name'].'-'.$data['nodeid'],'edit','node_manage');
    clear_cache_files(); // 清除相关的缓存文件
    sys_msg('修改节点成功',0,[['text'=>'修改节点成功！！！','link'=>'collection.php?act=node_manage']]);
}

/*------------------------------------------------------ */
//-- 删除节点
/*------------------------------------------------------ */
else if ($_REQUEST['act'] == 'node_delete')
{
    /* 权限判断 */
    admin_priv('node_manage');
	$sql="DELETE FROM {$ecs->table('collection_diyrule')} WHERE nodeid={$_REQUEST['nodeid']}";
	$db->query($sql);
	$sql="DELETE FROM {$ecs->table('collection_node')} WHERE id={$_REQUEST['nodeid']} LIMIT 1";
	$db->query($sql);
	clear_cache_files();
	if($db->affected_rows()==1)
	{
		admin_log($_REQUEST['nodeid'],'delete','node_manage');
		clear_cache_files(); // 清除相关的缓存文件
		$url = 'collection.php?act=node_manage';

		collect_goback($url);
	}
	else
		sys_msg('删除节点失败:'.$db->error());
}
/*------------------------------------------------------ */
//-- 复制节点
/*------------------------------------------------------ */
else if ($_REQUEST['act'] == 'node_copy')
{
	 /* 权限判断 */
    admin_priv('node_manage');
	
	$nodeid=$_REQUEST['cid'];
	$sql="SELECT * FROM {$ecs->table('collection_node')} WHERE id = {$nodeid}";
	$node=$db->getRow($sql);
	
	$sql="SELECT * FROM {$ecs->table('collection_diyrule')} WHERE nodeid = {$nodeid}";
	$attrs=$db->getAll($sql);
	
	$sql="SELECT * FROM {$ecs->table('collection_field')} WHERE nodeid = {$nodeid}";
	$fields=$db->getAll($sql);
	
	$sql="SELECT * FROM {$ecs->table('collection_replace')} WHERE nodeid = {$nodeid}";
	$replaces=$db->getAll($sql);
	
	unset($node['id']);
	$node['name']=$node['name'].'_'.time();
	$node=array_map(addslashes,$node);

	if($db->autoExecute($ecs->table('collection_node'), $node))
		$nodeid = $db->insert_id();
	else
		sys_msg('复制失败');
	
	if(!empty($attrs))
	{
		foreach($attrs as $v)
		{
			$v['nodeid']=$nodeid;
			unset($v['id']);
			$db->autoExecute($ecs->table('collection_diyrule'), $v);
		}
	}
	if(!empty($fields))
	{
		foreach($fields as $v)
		{
			$v['nodeid']=$nodeid;
			unset($v['id']);
			$db->autoExecute($ecs->table('collection_field'), $v);
		}
	}
	if(!empty($replaces))
	{
		foreach($replaces as $v)
		{
			$v['nodeid']=$nodeid;
			unset($v['id']);
			$db->autoExecute($ecs->table('collection_replace'), $v);
		}
	}
	admin_log($nodeid,'copy','node_manage');
	clear_cache_files();
	$url = 'collection.php?act=node_manage';
	collect_goback($url);
}

/*------------------------------------------------------ */
//-- 采集网址
/*------------------------------------------------------ */
else if ($_REQUEST['act'] == 'collection_url')
{
	 /* 权限判断 */
    admin_priv('node_collect');
	
	if(empty($_REQUEST['cid']))
		sys_msg('参数不正确');
	
	//获取采集配置
	$sql='SELECT * FROM '.$ecs->table('collection_node').' WHERE id = '.$_REQUEST['cid'];
	$node=$db->getRow($sql);
	if(empty($node))
		sys_msg('没有此项目');
	
	streamout('<h2>---网址采集---</h2>'); 
	
	/*序列网址*/
	if($node['sourcetype']=='1')
	{
		/*配置采集信息*/
		$url=$node['urlpage'];
		
		if(empty($url)||empty($node['pagesize_start'])||empty($node['pagesize_end']))
			die('配置信息不全，停止采集<br/>');
		
		for($i=$node['pagesize_start'];$i<=$node['pagesize_end'];$i+=$node['par_num'])
		{
			streamout( '<h2>------------第'.$i.'页--------------</h2>');
			$ready_url=str_replace('(*)',$i,$url);
			getUrls($ready_url,$node);
		}
	}
	/*多个网页*/
	else if($node['sourcetype']=='2')
	{
		if(empty(trim($node['urlpage_multi'],',')))
			die('配置信息不全，停止采集<br/>');
		
		$urls=explode(',',$node['urlpage_multi']);
		foreach($urls as $i=>$url)
		{
			streamout( '<h2>------------第'.$i.'页--------------</h2>');
			getUrls($url,$node);
		}
	}
	/*单一网页*/
	else if($node['sourcetype']=='3')
	{
		if(empty(trim($node['urlpage_single'])))
			die('配置信息不全，停止采集<br/>');
		streamout( '<h2>------------提取单页网址--------------</h2><br/>');
		getUrls($node['urlpage_single'],$node);
	}
	/*文本JSON*/
	else if($node['sourcetype']=='4')
	{
		if(empty(trim($node['urlpage'])))
			die('配置信息不全，停止采集<br/>');
		streamout( '<h2>------------提取JSON网址--------------</h2><br/>');
		getUrls($node['urlpage'],$node);
	}
	
	streamout('<br/><br/>------获取完成------<br/><br/>'); 
	admin_log(count($info['urls']),'collect','node_collect');
	clear_cache_files(); // 清除相关的缓存文件
}

/*------------------------------------------------------ */
//-- 通过网址采集内容
/*------------------------------------------------------ */
else if ($_REQUEST['act'] == 'collection_content')
{
	 /* 权限判断 */
    admin_priv('content_collect');
	
	set_time_limit(0);
	$_start=microtime(true);
	streamout('<h2>网址内容采集</h2><p style="color:red;">*正在采集时请勿关闭本页面，否则会导致中断<p>');
	
	//获取节点配置
	$sql="SELECT * FROM {$ecs->table('collection_node')} WHERE id = {$_REQUEST['cid']}";
	$rule=$db->getRow($sql);
	
	$per_num=intval($rule['per_collect_num']);
	//每次采集限制条数
	$limit_num=$per_num>0?' limit '.$per_num:'';
	
	streamout('<p>限制采集条数：'.($per_num>0?$per_num:'无限制').'</p>');
	
	//获取已采集的网址
	$sql='SELECT id,nodeid,url,title,sign FROM '.$ecs->table('collection_site').' WHERE is_read="0" and nodeid='.$_REQUEST['cid'].$limit_num;//.' limit 50';
	
	$sites=$db->getAll($sql);
	
	if(empty($sites))
		sys_msg('没有找到网址，请先采集网址');

	//获取通用规则
	//$sql='SELECT thumb_mulit_match,rule_goods_name,rule_shop_price,rule_brand,rule_goods_weight,rule_goods_desc,rule_goods_thumb,except_goods_name,except_shop_price,except_brand,except_goods_weight,except_goods_desc,except_goods_thumb FROM '.$ecs->table('collection_node').' WHERE id = '.$_REQUEST['cid'];
	
	//获取属性规则
	$sql='SELECT attrid ,attrname,rule_content,rule_except FROM '.$ecs->table('collection_diyrule').' WHERE nodeid = '.$_REQUEST['cid'];
	$diyrule=$db->getAll($sql);
	
	//获取额外字段
	$sql="SELECT * FROM {$ecs->table('collection_field')} WHERE nodeid = {$_REQUEST['cid']}";
	$fields=$db->getAll($sql);
	
	//获取公共替换规则
	$sql="SELECT * FROM {$ecs->table('collection_replace')} WHERE nodeid = {$_REQUEST['cid']}";
	$replaces=$db->getAll($sql);
	
	streamout('-------开始获取:'.date('Y-m-d H:i:s').'------<br/><br/>');

	foreach($sites as $k=>$site)
	{	
		streamout('<hr><br/>获取第'.($k+1).'条，网址标识：<b>'.$site['sign'].'</b> ...<br/>');
		
		$info=http_curl($site['url'],getCharset($rule['charset']));
		
		$_num=0;
		if(!empty($info['data']))
		{
			$rule['url']=$site['url'];
			$html=url_get_content($info['data'],$rule,$diyrule,$fields,$replaces);
			if($html)
			{
				$_num++;
				streamout( '已获取数据，等待插入<br/>');
				$common=addslashes(json_encode($html['common'],JSON_UNESCAPED_UNICODE));
				$attr=addslashes(json_encode($html['attr'],JSON_UNESCAPED_UNICODE));
				$comment=addslashes(json_encode($html['comment'],JSON_UNESCAPED_UNICODE));
				$imgpath=addslashes(json_encode($html['imgpath'],JSON_UNESCAPED_UNICODE));
		
				$sql="INSERT INTO {$ecs->table('collection_content')} (nodeid,siteid,title,common_content,attr_content,comment_info,imgpath) VALUES ({$site['nodeid']},{$site['id']},'{$site['title']}','{$common}','{$attr}','{$comment}','{$imgpath}')";
				$db->query($sql);
				if($_newid=$db->insert_id())
				{
					/*更新为已读*/
					$sql_isread="UPDATE {$ecs->table('collection_site')} SET is_read='1' WHERE id={$site['id']}";
					$db->query($sql_isread);
					streamout( "成功插入一条，ID：{$_newid}<br/><br/>");
				}
				else
					streamout( "插入失败：{$db->error()}<br/><br/>");
			}
			else
				streamout( "数据获取失败-------<br/><br/>");
		}
		else
			streamout('获取数据失败，获取下一条<br/>');
		//sleep(1);
	}
	$_end=microtime(true);

	/*更新采集节点采集时间*/
	$sql_update="UPDATE {$ecs->table('collection_node')} SET lastdate=".time()." WHERE id={$rule['id']}";
	if($db->query($sql_update))
		streamout('<br/><br/>-----更新节点采集时间---<br/><br/>');

	streamout('<br/><br/>----获取完成:'.date('Y-m-d H:i:s').'用时：'.($_end-$_start).'秒----<br/><br/>');
	admin_log($_num,'collect','content_collect');
	clear_cache_files(); // 清除相关的缓存文件
}

/*------------------------------------------------------ */
//-- 采集内容列表
/*------------------------------------------------------ */
else if ($_REQUEST['act'] == 'content_list')
{
	 /* 权限判断 */
    admin_priv('content_manage');
	
	clear_cache_files();

	/* 取得过滤条件 */
    $filter = array();
	$smarty->assign('ur_here',      '采集内容管理');
    $smarty->assign('full_page',    1);
    $smarty->assign('filter',       $filter);

	/*获取所有节点名*/
	$sql="SELECT id,name FROM {$ecs->table('collection_node')} ORDER BY id DESC";
	$node_list=$db->getAll($sql);
	
	/*获取所有商品类型*/
	$sql = "select cat_id,cat_name FROM {$ecs->table('goods_type')} WHERE enabled = 1";
    $good_types=$db->getAll($sql);
	
	/*获取所有商品分类*/
	//$sql = "select cat_id,cat_name FROM {$ecs->table('category')} WHERE enabled = 1";
    //$category=$db->getAll($sql);
	
	$cnts=get_collection_content_list(true);
	$list=$cnts['arr'];
	$smarty->assign('action_link2',  ['href' => 'collection.php?act=node_manage', 'text' => '返回节点列表']);
    $smarty->assign('filter',          $cnts['filter']);
	$smarty->assign('is_import',       $cnts['is_import']);
	$smarty->assign('keyword',         $cnts['keyword']);
    $smarty->assign('record_count',    $cnts['record_count']);
    $smarty->assign('page_count',      $cnts['page_count']);
	$smarty->assign('cat_id',          $cnts['filter']['cat_id']);
	$smarty->assign('cid',         	   $cnts['filter']['nodeid']);
	
    $sort_flag  = sort_flag($cnts['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);
	
	/*获取采集内容*/
	$smarty->assign('list',$list);
	$smarty->assign('nodes',$node_list);
	$smarty->assign('good_types',$good_types);
	
	/*获取商品分类数*/
	$cates=cat_list(0,0,false);
	foreach($cates as $k=>$v)
	{
		$cates[$k]['cat_name']=str_repeat('&nbsp;&nbsp;&nbsp;',$v['level']).$v['cat_name'];
	}
	$smarty->assign('category',$cates);

	//获得查询时间和次数，并赋值给smarty
	assign_query_info();
	$smarty->display('collection_content_list.htm');
}

/*------------------------------------------------------ */
//-- 采集内容翻页，排序
/*------------------------------------------------------ */
else if ($_REQUEST['act'] == 'content_query')
{
	//检查权限-JSON方式
    admin_priv('content_manage');

	$cnts=get_collection_content_list();
	$smarty->assign('list',			   $cnts['arr']);
    $smarty->assign('filter',          $cnts['filter']);
    $smarty->assign('record_count',    $cnts['record_count']);
    $smarty->assign('page_count',      $cnts['page_count']);
	$smarty->assign('is_import',       $cnts['is_import']);
	$smarty->assign('keyword',         $cnts['keyword']);
	$smarty->assign('cat_id',          $cnts['filter']['cat_id']);
	$smarty->assign('cid',         	   $cnts['filter']['nodeid']);

    $sort_flag  = sort_flag($cnts['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);
	
    make_json_result($smarty->fetch('collection_content_list.htm'), '',
        array('filter' => $cnts['filter'], 'page_count' => $cnts['page_count']));
}

/*------------------------------------------------------ */
//-- 采集内容批量操作
/*------------------------------------------------------ */
else if ($_REQUEST['act'] == 'contentbatch')
{
    if (isset($_POST['type']))
    {
		//批量删除
        if (strpos($_POST['type'],'batch_delete')===0)
        {
			if(!isset($_POST['checkboxes']) || !is_array($_POST['checkboxes']))
                sys_msg('没有选中数据', 1);
			
			//检查权限
			admin_priv('content_manage');
			if($_POST['type']=='batch_delete_withpic')
			{	
				/* 删除采集的图片文件 */
				$sql = "SELECT imgpath FROM " . $ecs->table('collection_content') .
						" WHERE id " . db_create_in(join(',', $_POST['checkboxes']));

				$res = $db->getAll($sql);
				if(!empty($res))
				{
					foreach ($res as $_rs)
					{
						$urls=json_decode($_rs['imgpath'],true);
						if(empty($urls))
							continue;
						foreach($urls as $url)
						{
							if(file_exists($url))
								@unlink($url);
						}
					}
				}
			}
			$sql = "DELETE FROM {$ecs->table('collection_content')} WHERE id " . db_create_in(join(',', $_POST['checkboxes']));
            if(!$db->query($sql))
				sys_msg('操作出错：'.$db->error());
            admin_log(join(',', $_POST['checkboxes']),$_POST['type'],'collection_content');
        }
		//所有删除
        else if (strpos($_POST['type'],'all_delete')===0)
        {
			//检查权限
			admin_priv('content_manage');
			$sql = "SELECT id,imgpath FROM {$ecs->table('collection_content')}";// WHERE nodeid = " .$_REQUEST['cid'];
			if($_POST['type']=='all_delete_withpic')
			{	
				/* 删除采集的图片文件 */
				$res = $db->getAll($sql);
				if(!empty($res))
				{
					foreach ($res as $_rs)
					{
						$urls=json_decode($_rs['imgpath'],true);
						if(empty($urls))
							continue;
						foreach($urls as $url)
						{
							if(file_exists($url))
								@unlink($url);
						}
					}
				}
			}
			$sql = "DELETE FROM " . $ecs->table('collection_content');
            if(!$db->query($sql))
				sys_msg('操作出错：'.$db->error());
            admin_log('all',$_POST['type'],'collection_content');
        }
		
		//批量导出
        else if ($_POST['type'] == 'batch_implode')
        {
			//检查权限
            admin_priv('content_implode');
			
            if (!isset($_POST['checkboxes']) || !is_array($_POST['checkboxes']))
                sys_msg('没有选中数据', 1);
			$category=empty($_POST['allcategory'])?$_POST['category']:$_POST['allcategory'];
            data_implode($_POST['checkboxes'],$category);
            admin_log(join(',', $_POST['checkboxes']),$_POST['type'],'content_manage');
        }
		//全部导出
        else if ($_POST['type'] == 'all_implode')
        {
            //检查权限
            admin_priv('content_implode');
            data_implode('',(empty($_POST['allcategory'])?false:$_POST['allcategory']));
            admin_log('all',$_POST['type'],'content_manage');
        }
		else
			sys_msg('无操作');
    }
    /* 清除缓存 */
    clear_cache_files();
   $url = 'collection.php?act=content_list&'.str_replace(['act=contentbatch','act=content_import'], '', $_SERVER['QUERY_STRING']);
   collect_goback($url);
}

/*------------------------------------------------------ */
//-- 导入采集内容
/*------------------------------------------------------ */
else if ($_REQUEST['act'] == 'content_import')
{
	//检查权限
	admin_priv('content_implode');
	data_implode($_REQUEST['contentid']);
	clear_cache_files(); // 清除相关的缓存文件
	admin_log($_REQUEST['contentid'],'implode','content_manage');
	//sys_msg('成功导入'.$_import_count.'个数据');
	$url = 'collection.php?act=content_list'.str_replace('act=content_import', '', $_SERVER['QUERY_STRING']);
	collect_goback($url);
}

/*------------------------------------------------------ */
//-- 删除采集内容
/*------------------------------------------------------ */
else if ($_REQUEST['act'] == 'content_delete')
{
	/*检查权限*/
	admin_priv('content_manage');
	
	if($_REQUEST['mode']=='all')
	{
		/* 删除采集的图片文件 */
		$sql = "SELECT imgpath FROM " . $ecs->table('collection_content') .
				" WHERE id =" . $_REQUEST['contentid'];

		$urls = $db->getOne($sql);
		$urls=json_decode($urls,true);
		if(!empty($urls))
		{
			foreach($urls as $url)
			{
				if(file_exists($url))
					@unlink($url);
			}
		}
	}
	$sql = "DELETE FROM " . $ecs->table('collection_content') ." WHERE id = " . $_REQUEST['contentid'];

	$res = $db->query($sql);
	admin_log($_REQUEST['contentid'],'delete','content_manage');
	clear_cache_files(); // 清除相关的缓存文件
	$url = 'collection.php?act=content_list&'.str_replace('act=content_delete', '', $_SERVER['QUERY_STRING']);
   collect_goback($url);
}

/*------------------------------------------------------ */
//-- 采集网址测试
/*------------------------------------------------------ */
else if ($_REQUEST['act'] == 'url_test')
{
	//检查权限*/
	admin_priv('node_test');
	
	set_time_limit(0);
	if(empty($_REQUEST['cid']))
		sys_msg('参数不正确');
	
	//获取采集配置
	$sql='SELECT * FROM '.$ecs->table('collection_node').' WHERE id = '.$_REQUEST['cid'];
	$node=$db->getRow($sql);
	if(empty($node))
		sys_msg('没有此项目');
	
	streamout('<h2>网址采集测试</h2>'); 
	
	/*序列网址*/
	if($node['sourcetype']=='1')
	{
		/*配置采集信息*/
		$url=$node['urlpage'];
		
		if(empty($url)||empty($node['pagesize_start'])||empty($node['pagesize_end']))
			die('配置信息不全，停止采集<br/>');

		for($i=$node['pagesize_start'];$i<=$node['pagesize_end'];$i+=$node['par_num'])
		{
			streamout('<hr/><h3>第'.$i.'页</h3>');
			$ready_url=str_replace('(*)',$i,$url);
			$info=getUrls($ready_url,$node,['ecs'=>$ecs,'db'=>$db],true);
			var_dump($info);
		}
	
	}
	/*多个网页*/
	else if($node['sourcetype']=='2')
	{
		if(empty(trim($node['urlpage_multi'],',')))
			die('配置信息不全，停止采集<br/>');
		
		$urls=explode(',',$node['urlpage_multi']);
		foreach($urls as $i=>$url)
		{
			streamout('<hr/><h3>第'.$i.'页</h3>');
			$info=getUrls($url,$node,['ecs'=>$ecs,'db'=>$db],true);
			var_dump($info);
		}
	}
	/*单一网页*/
	else if($node['sourcetype']=='3')
	{
		if(empty(trim($node['urlpage_single'])))
			die('配置信息不全，停止采集<br/>');
		$info=getUrls($node['urlpage_single'],$node,['ecs'=>$ecs,'db'=>$db],true);
		var_dump($info);
	}
	/*文本JSON*/
	else if($node['sourcetype']=='4')
	{
		if(empty(trim($node['urlpage'])))
			die('配置信息不全，停止采集<br/>');
		$info=getUrls($node['urlpage'],$node,['ecs'=>$ecs,'db'=>$db],true);
		var_dump($info);	
	}
	streamout('<br/><br/>----测试获取完成-----<br/><br/>');
}


/*------------------------------------------------------ */
//-- 单条采集内容测试
/*------------------------------------------------------ */
else if ($_REQUEST['act'] == 'content_test')
{
	//检查权限
	admin_priv('node_test');
	
	set_time_limit(0);
	$_start=microtime(true);
	$sql='SELECT id,nodeid,url,title,sign FROM '.$ecs->table('collection_site').' WHERE nodeid='.$_REQUEST['cid'].' limit 1';
	$site=$db->getRow($sql);
	if(empty($site))
		sys_msg('没有找到网址，请先采集网址');
	
	streamout('<h2>网址内容采集测试</h2>'); 
	
	$sql="SELECT * FROM {$ecs->table('collection_node')} WHERE id = {$_REQUEST['cid']}";
	$rule=$db->getRow($sql);
	
	//获取属性规则
	$sql='SELECT attrid,attrname,rule_content,rule_except FROM '.$ecs->table('collection_diyrule').' WHERE nodeid = '.$_REQUEST['cid'];
	$diyrule=$db->getAll($sql);
	
	//获取额外字段
	$sql="SELECT * FROM {$ecs->table('collection_field')} WHERE nodeid = {$_REQUEST['cid']}";
	$fields=$db->getAll($sql);
	
	//获取公共替换规则
	$sql="SELECT * FROM {$ecs->table('collection_replace')} WHERE nodeid = {$_REQUEST['cid']}";
	$replaces=$db->getAll($sql);
	
	$_start=time();
	
	streamout('<h3>网址标识：'.$site['sign'].'</h3>------开始获取:'.date('Y-m-d H:i:s').'------<br/><br/>');

	$info=http_curl($site['url'],getCharset($rule['charset']));

	if(!empty($info['data']))
	{
		streamout( '------获取数据成功，等待匹配------<br/>');
		$rule['url']=$site['url'];
		$html=TEST_url_get_content($info['data'],$rule,$diyrule,$fields,$replaces);
		$html=htmltrans($html);
		echo '<pre>';
		echo '<hr><h2>通用信息：</h2><br/>';
		print_r($html['common']);
		echo '<hr><h2>类型信息：</h2><br/>';
		print_r($html['attr']);
		echo '<hr><h2>评价信息：</h2><br/>';
		print_r($html['comment']);
		echo '</pre>';
	}
	else
		streamout('<h2>获取网页数据为空</h2>');
	$_end=microtime(true);
	streamout('<br/><br/>------获取完成:'.date('Y-m-d H:i:s').'用时：'.($_end-$_start).'秒（无入库，无下载图片）------<br/><br/>');
}

/*
导入内容
*/
function data_implode($ids='',$category=false)
{
	set_time_limit(0);
	$where='';
	if(is_array($ids))
		$where= "AND a.id " . db_create_in(join(',', $ids));
	else if(!empty($ids))
		$where="AND a.id=".$ids;

	$sql = "select a.id,a.common_content,a.attr_content,a.comment_info,b.url,c.is_gallery_download,c.desc_img_download,c.comment_img_download,c.comment_extimg_download,c.catid as typeid,c.is_create_brand 
			FROM {$GLOBALS['ecs']->table('collection_content')} a 
			LEFT JOIN {$GLOBALS['ecs']->table('collection_site')} b
			on b.id=a.siteid
			LEFT JOIN {$GLOBALS['ecs']->table('collection_node')} c
			on c.id=a.nodeid
			WHERE a.is_import='0' ".$where;

	$list=$GLOBALS['db']->getAll($sql);
	
	if(empty($list))
		sys_msg('没有可导出数据');
	
	$_import_count=0;
	foreach($list as $k=>$cnt)
	{
		$_common=filter(json_decode($cnt['common_content'],true));
		$_attr=filter(json_decode($cnt['attr_content'],true));
		$_comment=filter(json_decode($cnt['comment_info'],true));
		
		/*判断通用信息完整*/
		if(empty($_common))
		{
			streamout('没有商品信息数据，跳过此条</br></br>');
			continue;
		}
		
		/*判断是否已经有该商品*/
		$sql="SELECT count(goods_id) FROM {$GLOBALS['ecs']->table('goods')} WHERE goods_name='{$_common['goods_name']}'";
		if(intval($GLOBALS['db']->getOne($sql))>0)
		{
			streamout('该数据已经存在，跳过此条</br></br>');
			continue;
		}
		
		/*设置商品品牌*/
		$_brand=trim($_common['brand']);
		if(!empty($_brand))
		{
			$sql="SELECT brand_id FROM {$GLOBALS['ecs']->table('brand')} WHERE brand_name='{$_brand}'";
			$_bid=$GLOBALS['db']->getOne($sql);
			
			if(!empty($_bid))
			{
				$_common['brand_id']=$_bid;
			}	
			/*创建品牌*/
			else if(intval($cnt['is_create_brand'])===1)
			{
				streamout('创建品牌......');
				$sql="INSERT INTO {$GLOBALS['ecs']->table('brand')} (brand_name) VALUES ('{$_brand}')";
				if($GLOBALS['db']->query($sql))
				{
					$_common['brand_id']=$GLOBALS['db']->insert_id();
					streamout('成功<br/>');
				}
				else
				{
					streamout('失败，跳过此条<br/>');
					continue;
				}
			}
		}
		unset($_common['brand']);
		
		
		require_once(ROOT_PATH . '/' . ADMIN_PATH . '/includes/lib_goods.php');
		/*自动生成一个商品货号 */
		$goods_sn   = generate_goods_sn($GLOBALS['db']->getOne("SELECT MAX(goods_id) + 1 FROM ".$GLOBALS['ecs']->table('goods')));
		
		/*生成主图缩略图*/
		$main=makeImage($_common['goods_img'],true);
		if($main)
		{
			$_common['original_img']=$main[0]['original'];
			$_common['goods_img']=$main[0]['img'];
			$_common['goods_thumb']=$main[0]['thumb'];
		}
	
		/*保存相册数据信息*/
		$imgs=$_common['goods_gallery'];
		unset($_common['goods_gallery']);
		
		
		/*商品分类*/
		$cat_id=0;
		if(is_array($category))
		{
			if(!empty($category[$cnt['id']]))
				$cat_id=intval($category[$cnt['id']]);
		}
		else if(!empty($category))
			$cat_id=intval($category);
		
		/*插入商品信息*/
		$sql_goods = "INSERT INTO {$GLOBALS['ecs']->table('goods')} (".implode(',',array_keys($_common)).",goods_sn,goods_type,cat_id,is_on_sale) 
					VALUES ('".implode("','",array_values($_common))."','{$goods_sn}',{$cnt['typeid']},{$cat_id},0)";
		
		$GLOBALS['db']->query($sql_goods);
		
		$goods_id=$GLOBALS['db']->insert_id();
		
		/*如果插入失败，删除痕迹*/
		if(!$goods_id)
		{
			@unlink(ROOT_PATH.$_common['original_img']);
			@unlink(ROOT_PATH.$_common['goods_img']);
			@unlink(ROOT_PATH.$_common['goods_thumb']);
			streamout('导入商品信息失败:'.$GLOBALS['db']->error().'</br>跳过并删除本条数据图片文件<br/>');
			continue;
		}
		streamout('导入商品信息成功，goods_id'.$goods_id.'<br/>');
		
		
		/*插入商品属性信息*/
		if(!empty($_attr))
		{
			$sql_attr="INSERT INTO {$GLOBALS['ecs']->table('goods_attr')} (goods_id,attr_id,attr_value) VALUES ";
			
			foreach($_attr as $ak=>$av)
			{
				$sql_attr.="({$goods_id},{$av[0]},'{$av[1]}'),";
			}
			
			$GLOBALS['db']->query(rtrim($sql_attr,','));
			if($GLOBALS['db']->affected_rows()<=0)
				streamout('导入商品属性数据失败:'.$GLOBALS['db']->error().'</br>');
			else
				streamout('导入商品属性数据成功，条数:'.$GLOBALS['db']->affected_rows().'<br/>');
		}
		else
			streamout('没有商品属性数据</br>');
		
		
		/*插入商品评价*/
		if(!empty($_comment))
		{
			$sql_attr="INSERT INTO {$GLOBALS['ecs']->table('comment')} (id_value,user_name,content,comment_rank,add_time,status) VALUES ";
			
			foreach($_comment as $cv)
			{
				$sql_attr.="({$goods_id},'{$cv['user']}','{$cv['content']}','{$cv['rank']}','{$cv['time']}',1),";
			}
			
			$GLOBALS['db']->query(rtrim($sql_attr,','));
			if($GLOBALS['db']->affected_rows()<=0)
				streamout('导入商品评价数据失败:'.$GLOBALS['db']->error().'</br>');
			else
				streamout('导入商品评价数据成功，条数:'.$GLOBALS['db']->affected_rows().'<br/>');
			
		}
		
		/*生成相册缩略图*/
		//$imgs=makeImage(explode(';',$imgs));
		if($cnt['is_gallery_download'])
			$imgs=makeImage($imgs,false,true);
		/*导入相册*/
		if($imgs)
		{
			$sql_gallery = "INSERT INTO {$GLOBALS['ecs']->table('goods_gallery')} (goods_id,img_url,thumb_url,img_original) VALUES ";
			foreach($imgs as $k=>$v)
			{
				if($cnt['is_gallery_download'])
					$sql_gallery .= "({$goods_id},'{$v['img']}','{$v['thumb']}','{$v['original']}'),";
				else
					$sql_gallery .= "({$goods_id},'{$v}','{$v}','{$v}'),";
			}
			if(isset($main[0]['gallery'])&&!empty($main[0]['gallery']))
				$sql_gallery .= "({$goods_id},'','{$main[0]['gallery']}',''),";
			
			$GLOBALS['db']->query(rtrim($sql_gallery,','));
			if($GLOBALS['db']->affected_rows()<=0)
				streamout('导入相册失败:'.$GLOBALS['db']->error().'</br>');
			else
				streamout('导入相册成功，条数：'.$GLOBALS['db']->affected_rows().'<br/>');
		}
		else
			streamout('没有相册<br/>');
		
		
		/*设置采集信息为已读,更新详情id*/
		$sql="UPDATE {$GLOBALS['ecs']->table('collection_content')} SET is_import='1' , goods_id = {$goods_id} WHERE id={$cnt['id']} LIMIT 1";
		$GLOBALS['db']->query($sql);
		streamout('成功导入一个商品条目,ID:'.$goods_id.'<br/>------------------<br/>');
		$_import_count++;
	}
}

/*
获取网址url
*/
function getUrls($url,$node,$is_test=FALSE)
{
	$curl=http_curl($url,getCharset($node['sourcecharset']));
		
	if(empty($curl['data']))
	{
		$info['error']='Empty Html Data';
		return $info;
	}
	
	$urls=html_get_urls($curl['data'],$node);

	$info['urls']=$urls;
	
	if(empty($urls))
	{
		$info['error']='Empty Get Urls';
		return $info;
	}
	
	if($is_test)
	{
		return array_map(function($v){
			return complet_url($v['url'],$url);
		},$info['urls']);
	}

	$sql='INSERT INTO '.$GLOBALS['ecs']->table('collection_site').' (nodeid,sign,title,url) VALUES ';
	$IS_EMPTY=TRUE;
	$skipnum=$effectednum=0;
	if(!empty($node['page_sign_rule']))
		$page_sign_reg='/'.str_replace('<???>','([a-zA-Z0-9\-\_\,\.]+?)',preg_replace_callback('|[\/\\:\.\'\"\(\)\{\}\]\[\-]|',function($doc){return "\\".$doc[0];},str_replace('(*)','<???>',$node['page_sign_rule']))).'/U';	
	foreach($urls as $v)
	{
		$page_sign='';
		//获取网址标识
		if(!empty($page_sign_reg))
		{
			preg_match($page_sign_reg,$v['url'],$sign);
			if(isset($sign[1]))
				$page_sign=$sign[1];
		}
		/*如果url信息不全，则补全*/
		$_url=complet_url($v['url'],$url);

		/*检查是否已经有重复数据*/
		$sql_check="SELECT count(*) FROM {$GLOBALS['ecs']->table('collection_site')} WHERE ( url<>'' and url='{$_url}') or ( sign<>'' and sign='{$page_sign}')";
	
		if($GLOBALS['db']->getOne($sql_check)>0)
		{
			++$skipnum;
			streamout('跳过一条数据,标识：'.$page_sign.'，网址：'.$_url.'<br/>');
			continue;
		}
		$IS_EMPTY=FALSE;
		++$effectednum;
		$sql.="({$node['id']},'{$page_sign}','{$v['title']}','{$_url}'),";
	}

	$info['sql']=$sql;
	
	if($IS_EMPTY)
	{
		streamout('--------本页可插入数据为空----------<br/>');
		return false;
	}
	
	if($GLOBALS['db']->query(trim($sql,',')))
		streamout('----共获取'.count($urls).'条，成功插入'.$effectednum.'条数据，跳过'.$skipnum.'条----<br/>');
	
	else
		streamout('----插入出错：'.$GLOBALS['db']->error().'---------<br/>------共获取'.count($urls).'条，跳过'.$skipnum.'条----<br/>');

}





/*检查提交数据，并返回处理好的数据*/
function check_post_data($data,$is_check_name=false)
{
	$data=trim_all($data);
	
	if(empty($data))
		sys_msg('提交数据有误');
	
	$urlpage_multi=preg_replace('|(\s+)|',',',$data['urlpage_multi']);
	
	/*检验必填项*/
	if(empty($data['name']))
		sys_msg('请填写节点名');
	
	if($is_check_name)
	{
		$sql="SELECT count(id) FROM {$GLOBALS['ecs']->table('collection_node')} WHERE name='{$data['name']}'";
		if($GLOBALS['db']->getOne($sql)>0)
			sys_msg('节点名已存在');
	}
	if($data['sourcecharset']=='')
		sys_msg('请选择源页编码');
	if($data['sourcetype']=='')
		sys_msg('请选择源页类型');
	if(empty($data['catid']))
		sys_msg('请选择商品类型');
	
	/*设置checkbox开关项*/	
	$data['include_goods_desc']=isset($data['include_goods_desc'])?$data['include_goods_desc']:0;
	
	$data['desc_img_download']=isset($data['desc_img_download'])?intval($data['desc_img_download']):0;
	$data['comment_img_download']=isset($data['comment_img_download'])?intval($data['comment_img_download']):0;
	$data['comment_extimg_download']=isset($data['comment_extimg_download'])?intval($data['comment_extimg_download']):0;
	$data['is_gallery_download']=isset($data['is_gallery_download'])?intval($data['is_gallery_download']):0;
	
	$data['desc_data_jsonp']=isset($data['desc_data_jsonp'])?intval($data['desc_data_jsonp']):0;
	$data['is_comment_multiload']=isset($data['is_comment_multiload'])?intval($data['is_comment_multiload']):0;
	$data['is_timestamp_format']=isset($data['is_timestamp_format'])?intval($data['is_timestamp_format']):0;
	$data['is_gallery_async']=isset($data['is_gallery_async'])?intval($data['is_gallery_async']):0;
	$data['gallery_data_jsonp']=isset($data['gallery_data_jsonp'])?intval($data['gallery_data_jsonp']):0;
	$data['is_desc_lazyload']=isset($data['is_desc_lazyload'])?intval($data['is_desc_lazyload']):0;
	$data['desc_data_type']=isset($data['desc_data_type'])?intval($data['desc_data_type']):0;
	$data['comment_data_jsonp']=isset($data['comment_data_jsonp'])?intval($data['comment_data_jsonp']):0;
	$data['per_collect_num']=isset($data['per_collect_num'])?intval($data['per_collect_num']):0;
	
	
	return $data;

}